
import datetime ,time
import json
from django.core import serializers
from django.shortcuts import render,HttpResponse
from django.http import  JsonResponse
from django.db.models import Q


from messageDisplay.models import cInformation, ProductDetail, HardDetail, Advise, BasicSensor, PictureM

def Caltime(date1,date2):
    date1=time.strptime(date1,"%Y-%m-%d")
    date2=time.strptime(date2,"%Y-%m-%d")
    date1=datetime.datetime(date1[0],date1[1],date1[2])
    date2=datetime.datetime(date2[0],date2[1],date2[2])
    return date2-date1
# Create your views here.
# url(r'^index.html$', views.index),
def index(request):
    """首页视图函数"""
    return render(request, 'index.html')

# url(r'^graphs.html$', views.graphs),
def graphs(request):
    """首页视图函数"""
    return render(request, 'graphs.html')

#url(r'^gallery.html$', views.gallery),
def gallery(request):
    """首页视图函数"""
    return render(request, 'gallery.html')

# url(r'^maps.html$', views.maps),
def maps(request):
    """首页视图函数"""
    return render(request, 'maps.html')

# url(r'^typography.html$', views.typography),
def typography(request):
    """首页视图函数"""
    return render(request, 'typography.html')

# url(r'^inbox.html$', views.inbox),
def inbox(request):
    """首页视图函数"""
    return render(request, 'inbox.html')

# url(r'^404.html$', views.page_not_found),
def page_not_found(request):
    """首页视图函数"""
    return render(request, '404.html')

# url(r'^faq.html$', views.faq),
def faq(request):
    """首页视图函数"""
    return render(request, 'faq.html')

# url(r'^blank.html$', views.blank),
def blank(request):
    """首页视图函数"""
    return render(request, 'blank.html')

# url(r'^layout.html$', views.layout),
def layout(request):
    """首页视图函数"""
    return render(request, 'layout.html')

# url(r'^forms.html$', views.forms),
def forms(request):
    """首页视图函数"""
    return render(request, 'forms.html')

# url(r'^validation.html$', views.validation),
def validation(request):
    """首页视图函数"""
    return render(request, 'validation.html')

# calendar.html
def calendar(request):
    """calender"""
    return render(request,'calendar.html')

# url(r'^profile.html$', views.profile),
def profile(request):
    """profile html"""
    return render(request,'profile.html')




# url(r'^signin.html$', views.signin),
def signin(request):
    """首页视图函数"""
    return render(request, 'signin.html')


# url(r'^signup.html$', views.signup),
def signup(request):
    """首页视图函数"""
    return render(request, 'signup.html')


# url(r'^consumers.html$', views.consumers),
def consumers(request,num):
    """consumers views"""
    goodsId = int(num)
    if ProductDetail.objects.filter(proCode__exact=goodsId):
        goodsInfo = ProductDetail.objects.filter(proCode__exact=goodsId)[0]
        manEnterprise = int(str(goodsInfo.manEnterprise).split(':')[1])
        manEnterpriseInfo = cInformation.objects.filter(userCode__exact=manEnterprise)[0]
        transInfo =  cInformation.objects.filter(userCode__exact=int(goodsInfo.transer))[0]
        if goodsInfo.superer:
            supererInfo = cInformation.objects.filter(userCode__exact=int(goodsInfo.superer))[0]
        else:
            supererInfo = ''
        manDate = str(goodsInfo.manDate)
        curTime = '20'+datetime.date.today().strftime('%y-%m-%d')
        date_ = str(Caltime(manDate,curTime)).split(" ")[0]
        if int(date_) > int(goodsInfo.expDate):
            data_ = 0
            date_ = 0
        else:
            date_ = int(goodsInfo.expDate) - int(date_)
            data_ = int(date_/int(goodsInfo.expDate)*100)
        expirate = {'date': date_, 'data': data_}


        data = {'goodsInfo':goodsInfo,'manEnterpriseInfo':manEnterpriseInfo,'transInfo':transInfo,'supererInfo':supererInfo,'expirate':expirate}
        return render(request,'consumers.html',data)
    else:
        return render(request,'404.html')

def vehicle(request,num):
    """consumers views"""
    vehicleDetail = cInformation.objects.filter(userCode__exact=num)[0]
    hardInfo = vehicleDetail.harddetail_set.all()[0]
    vehicleGoods = ProductDetail.objects.filter(transerSensor__exact=hardInfo.hardCode).filter(supererSnesor__exact=None).order_by("evaluate")
    totalCount = vehicleGoods.count()
    hearywaringCount = vehicleGoods.filter(evaluate__lte=3).count()
    normalCount = vehicleGoods.filter(evaluate__lte = 7).filter(evaluate__gt=3).count()
    data = {'hardInfo':hardInfo,'hearywaringCount':hearywaringCount,'totalCount':totalCount,
            'normalCount':normalCount,'vehicleDetail':vehicleDetail}
    return render(request,'vehicle.html',data)

def ajax_init_list(request):
    vehicleNum = request.POST.get('vehicleNum')
    goods = ProductDetail.objects.filter(Q(transer__exact=vehicleNum) & (Q(superer__exact=None)|Q(superer__exact=''))).order_by("evaluate")
    goodsCount = len(goods)
    json_data = serializers.serialize('json', goods)
    json_data = json.loads(json_data)
    data = {'json_data':json_data,"goodsCount":goodsCount}
    return JsonResponse(data, safe=False)

def ajax_super_inint_list(request):
    superNum = request.POST.get('superNum')
    goods = ProductDetail.objects.filter(superer__exact=superNum).order_by("evaluate")
    goodsCount = len(goods)
    json_data = serializers.serialize('json', goods)
    json_data = json.loads(json_data)
    for e in json_data:
        e['fields']['manEnterprise'] = cInformation.objects.get(id = e['fields']['manEnterprise']).userName
        if e['fields']['evaluate']>=4 and e['fields']['evaluate']<=6 :
            e['fields']['opAdvies'] = '尽快销售'
        elif e['fields']['evaluate']>=2 and e['fields']['evaluate']<=3 :
            e['fields']['opAdvies'] = '下架'
        elif e['fields']['evaluate'] <= 1:
            e['fields']['opAdvies'] = '退货'
        else:
            e['fields']['opAdvies'] = ''
    # json_data[0]['fields']['manEnterprise']
    data = {'json_data': json_data, "goodsCount": goodsCount}
    return JsonResponse(data, safe=False)

# url(r'^supermaket.html$', views.supermaket),
def supermaket(request,num):
    """supermaket views"""
    superDetail = cInformation.objects.filter(userCode__exact=num)[0]
    hardInfo = superDetail.harddetail_set.all()
    hardIdList = []
    for e in hardInfo:
        hardIdList.append(e.hardCode)
    superGoods = ProductDetail.objects.filter(superer__exact=superDetail.userCode).order_by("evaluate")
    totalCount = len(superGoods)
    proTotal = {}
    proTotal['totalCount'] =totalCount
    proTotal['waitReturn'] = superGoods.filter(evaluate__lte=1).count()
    proTotal['waitReturnCount'] = int((proTotal['waitReturn']/totalCount)*100)
    proTotal['downDisplay'] = superGoods.filter(evaluate__lte=3).filter(evaluate__gt=1).count()
    proTotal['downDisplayCount'] = int((proTotal['downDisplay'] / totalCount) * 100)
    proTotal['proWaring'] = superGoods.filter(evaluate__lt = 7).filter(evaluate__gt=3).count()
    proTotal['proWaringCount'] = int((proTotal['proWaring'] / totalCount) * 100)
    proTotal['proWell'] = superGoods.filter(evaluate__gte=7).count()
    proTotal['proWellCount'] = int((proTotal['proWell'] / totalCount) * 100)
    advise = {}
    hard = {}
    totalProAdvise = []
    for e in superGoods:
        sigalProAdvise = e.advise_set.all()
        totalProAdvise += sigalProAdvise
    advise['totalProAdvise'] = totalProAdvise
    deal = []
    dealing = []
    finish = []
    returnA = []
    deleteA = []
    dealcount = 0
    dealingcount = 0
    finishcount = 0
    returnAcount = 0
    deleteAcount = 0
    for k in totalProAdvise:
        if k.isDel:
            deleteA.append(k)
            deleteAcount += 1
            continue
        if k.adDealFinish:
            finish.append(k)
            finishcount+=1
            continue
        if k.adDealSupermarket is None :
            deal.append(k)
            dealcount =  dealcount + 1
        else:
            if k.adDealManger is None:
                dealing.append(k)
                dealingcount +=1
            else:
                if k.adReturn is False:
                    dealing.append(k)
                    dealingcount += 1
                else:
                    dealing.append(k)
                    dealingcount += 1
                    returnA.append(k)
                    returnAcount += 1
    advise['dealcount'] = dealcount
    advise['dealingcount'] = dealingcount
    advise['finishcount'] = finishcount
    advise['returnAcount'] = returnAcount
    advise['deleteAcount'] = deleteAcount
    advise['deal'] = deal
    advise['dealing'] = dealing
    advise['finish'] = finish
    advise['returnA'] = returnA
    advise['deleteA'] = deleteA
    data = {'hardIdList':hardIdList,'superId':num,'proTotal':proTotal,'advise':advise,'hard':hard}
    return render(request,'supermaket.html',data)


#url(r'^managers.html$', views.managers),
def managers(request,num):
    """manager.html"""
    proInfo =[]
    totalProAdvise = []
    advise = {}
    superInfo = cInformation.objects.filter(userManager__exact=num).filter(userCategory__exact='商超')
    for e in superInfo:
        k =ProductDetail.objects.filter(superer__exact=str(e.userCode))
        proInfo += k
    for i in proInfo:
        g = i.advise_set.all()
        totalProAdvise += g
    advise['totalProAdvise'] = totalProAdvise
    deal = []
    finish = []
    returnA = []
    dealcount = 0
    finishcount = 0
    returnAcount = 0
    for k in totalProAdvise:
        if k.adDealFinish:
            finish.append(k)
            finishcount+=1
            continue
        if k.adDealSupermarket is None :
            deal.append(k)
            dealcount =  dealcount + 1
        else:
            if k.adReturn:
                returnA.append(k)
                returnAcount += 1
    advise['dealcount'] = dealcount
    advise['finishcount'] = finishcount
    advise['returnAcount'] = returnAcount
    advise['deal'] = deal
    advise['finish'] = finish
    advise['returnA'] = returnA
    data = { 'managerId': num, 'advise': advise}
    return render(request,'managers.html',data)

def ajax_manager_list(requset):
    # num = requset.POST.get('num')
    num =int(requset.POST.get('num'))
    if num == 1:
        goods = ProductDetail.objects.all()
    elif num == 2:
        goods =cInformation.objects.filter(userCategory__exact='商超')
    elif num == 3:
        goods = cInformation.objects.filter(userCategory__exact='运输')
    elif num == 4:
        goods = cInformation.objects.filter(userCategory__exact='生产')
    elif num == 5:
        goods = Advise.objects.all()
    goodsCount = goods.count()
    json_data = serializers.serialize('json', goods)
    json_data = json.loads(json_data)
    data = {'json_data': json_data, "goodsCount": goodsCount}
    return JsonResponse(data, safe=False)


def ajax_signin_search_handle(request):

    goodsId = int(request.POST.get('goodsId'))

    if  ProductDetail.objects.filter(proCode__exact = goodsId ):
        return JsonResponse({'res':'1'})
    else:
        return JsonResponse({'res':'0'})


def ajax_signin_user_handle(request):

    count = int(request.POST.get('count'))
    pwd =request.POST.get('pwd')
    list = cInformation.objects.filter(userCode__exact = count )
    if  list:
        if list[0].userPasswd == pwd :
            # print(list[0].userPasswd+'-------------')
            if list[0].userCategory == '生产':
                return JsonResponse({'res':'1','userType':'0'})
            if list[0].userCategory == '运输':
                return JsonResponse({'res':'1','userType':'1'})
            if list[0].userCategory == '商超':
                return JsonResponse({'res':'1','userType':'2'})
            if list[0].userCategory == '监管':
                return JsonResponse({'res':'1','userType':'3'})
        else:
            return JsonResponse({'res': '0'})
    else:
        return JsonResponse({'res':'0'})

def ajax_change_pwd(request):
    count = int(request.POST.get('count'))

    pwd = request.POST.get('pwd')
    print(pwd)
    try:
        change_row = cInformation.objects.filter(userCode__exact=count)[0]
        change_row.userPasswd = pwd
        change_row.save()
    except Exception as res:
        print('this is a database read or write error:%s'% res)
        return JsonResponse({'res': '0'})
    else:
        return JsonResponse({'res': '1'})

def ajax_get_temp_hum(request):
    hardId = int(request.POST.get('hardId'))
    tempData = []
    humData = []
    hard = HardDetail.objects.filter(hardCode__exact = hardId)[0]
    tempList = hard.basicsensor_set.filter(sensorName__exact='温度传感器').order_by('sensorDate')
    humList = hard.basicsensor_set.filter(sensorName__exact='湿度传感器').order_by('sensorDate')
    # tempList = BasicSensor.objects.filter(sensorName__exact='温度传感器').filter(sensorHard__exact=hardId)
    i = 1
    tempTotal = 0
    j = 1
    humtotal = 0
    # humList = BasicSensor.objects.filter(sensorName__exact='湿度传感器').filter(sensorHard__exact=hardId)
    for temp in tempList:
        tempData.append([i,float(temp.sensorData)])
        tempTotal = tempTotal + float(temp.sensorData)
        # print("----------------"+str(temp))
        i = i+1
    for hum in humList:
        humData.append([j,float(hum.sensorData)])
        humtotal = humtotal + float(hum.sensorData)
        j = j+1
    avgtempData = round(tempTotal/(i -1),2)
    avghumData = round(humtotal /(j -1) , 2)
    return JsonResponse({'tempData':tempData,'humData':humData,'avgtempData':avgtempData,'avghumData':avghumData})

#/ajax_check_advise
def ajax_check_advise(request):
    goodsId = int(request.POST.get('goodsId'))
    ad = ProductDetail.objects.filter(proCode__exact=goodsId)[0].advise_set.all()
    if ad:
        if ad[0].adDealSupermarket:
            if ad[0].adDealManger:
                if ad[0].adDealFinish:
                    return JsonResponse({'res':1,"adDealSupermarket":1,'adDealManger':1,'adDealFinish':1})
                else:
                    return JsonResponse({'res': 1, "adDealSupermarket": 1, 'adDealManger': 1,'adDealFinish':0})
            else:
                return JsonResponse({'res':1,"adDealSupermarket":1,'adDealManger':0})
        else:
            return JsonResponse({'res':1,"adDealSupermarket":0})
    else:
        return JsonResponse({"res":0})


def ajax_consumers_submit(request):
    # 'data':{'subName':$subName,'goodsId':$goodsId,
    #         'subTel':$subTel,'subMail':$subMail,
    #         'subIdCard':$subIdCard,'subContent':$subContent}
    adName = request.POST.get('subName')
    adDoods = int(request.POST.get('goodsId'))
    adTel = int(request.POST.get('subTel'))
    adMail = request.POST.get('subMail')
    adIdCard = request.POST.get('subIdCard')
    adConsumerText = request.POST.get('subContent')
    d1 = ProductDetail.objects.get(proCode=adDoods)
    u1 = Advise(adName=adName, adDoods=d1, adTel=adTel, adMail=adMail, adIdCard=adIdCard,
                adConsumerText=adConsumerText)
    try:
        u1.save()
        return JsonResponse({'res': '1'})
    except Exception as res:
        print("" + res)
        return JsonResponse({'res': '0'})

def set_cookie_consumers(request):
    response = HttpResponse('set coookie')
    response.set_cookie('goodsId',1,max_age=3600*24*7)
    return  response

def get_cookie_consumers(request):
    num = request.COOKIES['goodId']
    return HttpResponse(num)

def set_session(request):
    request.session['username'] = 'smart'
    request.session['pwd'] = '1'
    return HttpResponse('set session')

def get_session(request):
    username = request.session['username']
    pwd = request.session['pwd']
    return HttpResponse(username + "|"+ pwd)




